package com.neusoft.neuiotms.dcom.controller;

import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.neusoft.bizcore.auth.common.bean.UserBean;
import com.neusoft.bizcore.web.dto.result.PageResultDTO;
import com.neusoft.bizcore.web.dto.result.ResultDTO;
import com.neusoft.bizcore.web.dto.result.ResultListDTO;
import com.neusoft.bizcore.web.support.Searchable;
import com.neusoft.neuiotms.dcom.dto.MonthServiceSummaryDTO;
import com.neusoft.neuiotms.dcom.dto.MonthUnfinishedItemDescDTO;
import com.neusoft.neuiotms.dcom.dto.MonthValueAddedDTO;
import com.neusoft.neuiotms.dcom.dto.MonthWeeklyDTO;
import com.neusoft.neuiotms.dcom.service.MonthServiceSummaryService;
import com.neusoft.neuiotms.dcom.service.MonthUnfinishedItemDescService;
import com.neusoft.neuiotms.dcom.service.MonthValueAddedService;
import com.neusoft.neuiotms.dcom.service.MonthWeeklyService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

@Api(tags = "月报管理")
@RestController
@Slf4j
@RequestMapping(value = "/api/w/monthWeekly")
public class MonthWeeklyController {

    @Autowired
    private MonthWeeklyService monthWeeklyService;
    @Autowired
    private MonthUnfinishedItemDescService monthUnfinishedItemDescService;
    @Autowired
    private MonthValueAddedService monthValueAddedService;
    @Autowired
    private MonthServiceSummaryService monthServiceSummaryService;

    @ApiOperation("查询所有月报")
    @GetMapping
    public ResultListDTO<MonthWeeklyDTO> index(final Searchable searchable, final UserBean userBean) {
        return ResultListDTO.success(this.monthWeeklyService.index(searchable, userBean));
    }

    @ApiOperation("分页查询所有月报")
    @GetMapping("/p")
    public PageResultDTO<MonthWeeklyDTO> search(final Pageable pageable, final Searchable searchable,
            final UserBean userBean) {
        return PageResultDTO.success(this.monthWeeklyService.search(pageable, searchable, userBean));
    }

    @ApiOperation("创建月报")
    @PostMapping("")
    public ResultDTO<MonthWeeklyDTO> create(@RequestBody final MonthWeeklyDTO dto) {
        return ResultDTO.success(this.monthWeeklyService.create(dto));
    }

    @ApiOperation(value = "修改月报")
    @PutMapping("/{id}")
    public ResultDTO<MonthWeeklyDTO> update(@PathVariable final Long id,
            @RequestBody final MonthWeeklyDTO dto) {
        return ResultDTO.success(this.monthWeeklyService.update(id, dto));
    }

    @ApiOperation("月报详情")
    @GetMapping("/{id}")
    public ResultDTO<MonthWeeklyDTO> details(@PathVariable final Long id) {
        return ResultDTO.success(this.monthWeeklyService.details(id));
    }

    @ApiOperation("删除月报")
    @DeleteMapping("/{id}")
    public ResultDTO<Void> delete(@PathVariable final Long id) {
        this.monthWeeklyService.delete(id);
        return ResultDTO.success();
    }

    @ApiOperation("根据月报ID查询月报未完成项")
    @GetMapping("/unfinished/items/{id}")
    public ResultListDTO<MonthUnfinishedItemDescDTO> unfinishedItems(@PathVariable final Long id) {
        return ResultListDTO.success(this.monthUnfinishedItemDescService.getInfoByMonthWeeklyId(id));
    }

    @ApiOperation(value = "修改月报未完成项")
    @PutMapping("/unfinished/items/{id}")
    public ResultListDTO<MonthUnfinishedItemDescDTO> update(@PathVariable final Long id,
            @RequestBody final List<MonthUnfinishedItemDescDTO> dtos) {
        return ResultListDTO.success(this.monthUnfinishedItemDescService.update(id, dtos));
    }

    @ApiOperation("根据月报ID查询月报增值服务")
    @GetMapping("/valueadded/{id}")
    public ResultListDTO<MonthValueAddedDTO> valueadded(@PathVariable final Long id) {
        return ResultListDTO.success(this.monthValueAddedService.getInfoByMonthId(id));
    }

    @ApiOperation(value = "修改月报增值服务")
    @PutMapping("/valueadded/{id}")
    public ResultListDTO<MonthValueAddedDTO> updateValueAdded(@PathVariable final Long id,
            @RequestBody final List<MonthValueAddedDTO> dtos) {
        return ResultListDTO.success(this.monthValueAddedService.update(id, dtos));
    }

    @ApiOperation("根据月报ID查询服务工作量总结")
    @GetMapping("/servicesummary/{id}")
    public ResultListDTO<MonthServiceSummaryDTO> serviceSummary(@PathVariable final Long id) {
        return ResultListDTO.success(this.monthServiceSummaryService.getInfoByMonthId(id));
    }

    @ApiOperation(value = "修改月报服务工作量总结")
    @PutMapping("/servicesummary/{id}")
    public ResultListDTO<MonthServiceSummaryDTO> updateServiceSummary(@PathVariable final Long id,
            @RequestBody final List<MonthServiceSummaryDTO> dtos) {
        return ResultListDTO.success(this.monthServiceSummaryService.update(id, dtos));
    }

    @ApiOperation("导出月报")
    @GetMapping(value = "/export/{id}")
    public void download(@PathVariable final Long id, final HttpServletResponse response) {

        final XWPFDocument xfc = this.monthWeeklyService.export(id);
        OutputStream out = null;
        try {
            out = response.getOutputStream();
            response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
            response.setHeader("Content-disposition",
                    String.format("attachment; filename=%s",
                            URLEncoder.encode("项目服务月报" + LocalDateTime.now() + ".docx", "UTF-8")));
            xfc.write(out);
            out.flush();
        } catch (final Exception e) {
            MonthWeeklyController.log.error("项目服务月报导出失败", e);
        } finally {
            try {
                out.close();
            } catch (final IOException e) {
                MonthWeeklyController.log.error("项目服务月报导出关闭流失败", e);
            }
        }
    }

    @ApiOperation("运维周报统计")
    @GetMapping("/stats")
    public ResultDTO<?> todayStats() {
        final Map<String, Long> result = this.monthWeeklyService.reportStats();
        return ResultDTO.success(result);
    }

    @ApiOperation("月报统计报表")
    @GetMapping("/stats/report")
    public PageResultDTO<Map<String, Object>> reportStats(final Pageable pageable,
            @RequestParam(required = false) final String username,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") final Date start,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") final Date end) {
        final Page<Map<String, Object>> result = this.monthWeeklyService.report(pageable, username, start, end);
        return PageResultDTO.success(result);
    }

    @ApiOperation("导出月报统计")
    @GetMapping(value = "/stats/export")
    public void exportStats(@RequestParam(required = false) final String username,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") final Date start,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") final Date end,
            final HttpServletResponse response) {

        final Workbook workbook = this.monthWeeklyService.exportReport(username, start, end);
        OutputStream out = null;
        try {
            out = response.getOutputStream();
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setHeader("Content-disposition",
                    String.format("attachment; filename=%s",
                            URLEncoder.encode("月报统计导出" + LocalDateTime.now() + ".xlsx", "UTF-8")));
            workbook.write(out);
            out.flush();
        } catch (final Exception e) {
            MonthWeeklyController.log.error("月报统计导出失败", e);
        } finally {
            try {
                out.close();
            } catch (final IOException e) {
                MonthWeeklyController.log.error("月报统计导出关闭流失败", e);
            }
        }
    }

    @ApiOperation("月报提醒测试")
    @GetMapping("/notice/test")
    public ResultDTO<?> noticeTest() {
        this.monthWeeklyService.checkReportNotice();
        return ResultDTO.success();
    }

}
